import React, { useEffect, useRef } from 'react';
import { Card } from 'antd';
import * as echarts from 'echarts';
import type { ApiRiskAnalysis } from '../../../services/apiStatistics';

interface ApiRiskAnalysisChartProps {
    data: ApiRiskAnalysis | null;
    loading?: boolean;
}

const ApiRiskAnalysisChart: React.FC<ApiRiskAnalysisChartProps> = ({ data, loading = false }) => {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstance = useRef<echarts.ECharts | null>(null);

    useEffect(() => {
        if (!chartRef.current || loading || !data) return;

        // 初始化图表
        if (!chartInstance.current) {
            chartInstance.current = echarts.init(chartRef.current);
        }

        // 准备风险等级数据，确保data和riskDistribution存在
        const riskCategories = (data?.riskDistribution || []).map(item => item.displayName || item.level);
        const riskCounts = (data?.riskDistribution || []).map(item => item.count);
        const riskColors = (data?.riskDistribution || []).map(item => getRiskColor(item.level));

        const option = {
            title: {
                text: 'API风险等级分布',
                left: 'center',
                top: '5%',
                textStyle: {
                    fontSize: 24,
                    fontWeight: 'bold',
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params: any) {
                    const item = params[0];
                    const percentage = (data?.riskDistribution || [])[item.dataIndex]?.percentage || 0;
                    return `${item.name}<br/>${item.seriesName}: ${item.value}个 (${percentage}%)`;
                }
            },
            grid: {
                left: '10%',
                right: '10%',
                bottom: '15%',
                top: '20%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: riskCategories,
                axisLabel: {
                    interval: 0,
                    rotate: 45,
                    fontSize: 24,  // 进一步增大X轴标签字体
                    color: '#666'
                },
                axisLine: {
                    lineStyle: {
                        color: '#e0e0e0'
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: 'API数量',
                nameTextStyle: {
                    color: '#666',
                    fontSize: 24  // 进一步增大Y轴名称字体
                },
                axisLabel: {
                    fontSize: 22,  // 进一步增大Y轴标签字体
                    color: '#666'
                },
                axisLine: {
                    lineStyle: {
                        color: '#e0e0e0'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: '#f0f0f0',
                        type: 'dashed'
                    }
                }
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: riskCounts.map((count, index) => ({
                        value: count,
                        itemStyle: {
                            color: riskColors[index],
                            borderRadius: [4, 4, 0, 0]
                        }
                    })),
                    barWidth: '60%',
                    label: {
                        show: true,
                        position: 'top',
                        fontSize: 24,  // 进一步增大柱状图标签字体
                        color: '#333',
                        fontWeight: 'bold'
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.3)'
                        }
                    },
                    animationDelay: function (idx: number) {
                        return idx * 100;
                    }
                }
            ]
        } as any;

        chartInstance.current.setOption(option);

        // 监听窗口大小变化
        const handleResize = () => {
            chartInstance.current?.resize();
        };
        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [data, loading]);

    // 组件卸载时销毁图表
    useEffect(() => {
        return () => {
            if (chartInstance.current) {
                chartInstance.current.dispose();
                chartInstance.current = null;
            }
        };
    }, []);

    // 获取风险等级对应的颜色
    const getRiskColor = (level: string): string => {
        const colorMap: { [key: string]: string } = {
            'EXTREME_RISK': '#ff4d4f',
            'HIGH_RISK': '#fa8c16',
            'MEDIUM_RISK': '#fadb14',
            'LOW_RISK': '#52c41a',
            'MINIMAL_RISK': '#1890ff',
            'UNKNOWN': '#d4d4d4'
        };
        return colorMap[level] || '#667eea';
    };

    return (
        <Card 
            size="small" 
            loading={loading}
            style={{ 
                height: '400px',
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}
            bodyStyle={{ height: '100%', padding: '16px' }}
        >
            <div 
                ref={chartRef} 
                style={{ 
                    width: '100%', 
                    height: '100%'
                }}
            />
        </Card>
    );
};

export default ApiRiskAnalysisChart;